<script setup lang="ts">
import type { BubbleListProps } from "vue-element-plus-x/types/BubbleList";
import {
  DocumentCopy,
  Refresh,
  Remove,
  Search,
  Star,
} from "@element-plus/icons-vue";
import { ref, provide, watch, inject } from "vue";
import { clearMessageList, getChatList, removeMessage } from "@/api/chat";
import { useRoute } from "vue-router";
import { useUserStore } from "@/stores";
// import AiChatContent from "../../topic/AiChatContent.vue";
import { aiTopic } from "@/stores/aiTopicPinia/aiTopic";
import { formatDate } from "@/utils/common";
import { ElMessage } from "element-plus";
// 初始化 store
const aiTopics = aiTopic();
defineProps({
  height: {
    type: String,
    default: "60vh",
  },
});
const isLoading = ref(false);
const bubbleListRef = ref();
const router = useRoute();
console.log("router", router.params.roomId);
function scrollBottom() {
  console.log("scrollToBottom========================");
  // 滚动BubbleList组件内部
  if (bubbleListRef.value && bubbleListRef.value.scrollToBottom) {
    bubbleListRef.value.scrollToBottom();
  }

  // 同时滚动外层容器到底部
  setTimeout(() => {
    const chatContainer =
      document.querySelector(".dragged-panel .chat-messages") ||
      document.querySelector(".right-panel .chat-messages");
    if (chatContainer) {
      chatContainer.scrollTop = chatContainer.scrollHeight;
    }
  }, 50);
}
const userStore = useUserStore();
const avatar = ref(
  "https://cube.elemecdn.com/0/88/03b0d39583f48206768a7534e55bcpng.png"
);

// 获取父组件传递的重新启用提交按钮的函数
const enableSubmitBtn = inject<() => void>("enableSubmitBtn");
const avartAi = ref(
  "https://cube.elemecdn.com/0/88/03b0d39583f48206768a7534e55bcpng.png"
);
const getMessageLIstHandler = async () => {
  const getMessageList = await getChatList(userStore.currentUser.userId);
  console.log(getMessageList.data);

  for (let i = 0; i < getMessageList.data.length; i++) {
    generateMessageItem(
      getMessageList.data[i].messageType.toLowerCase(),
      getMessageList.data[i].messageType.toLowerCase() == "assistant"
        ? "start"
        : "end",
      getMessageList.data[i].text,
      getMessageList.data[i].metadata.id,
      getMessageList.data[i].metadata.createTime,
      false
    );
  }
  autoSendMessage();
};
if (userStore.isLoggedIn) {
  avatar.value = userStore.currentUser.avatarUrl;
  getMessageLIstHandler();
}

// 题目类型定义
interface Question {
  id: string;
  question: string;
  options: string[];
  correctAnswerIndex: number;
  explanation?: string;
}
// 存储解析后的题目数据
const questions = ref<Question[]>([]);

interface Message extends BubbleListProps {
  key: number;
  role: string;
  id: string;
  loading: boolean;
  content: string;
  placement: string;
}
const parseQuestions = (markdown: string): Question[] => {
  const questions: Question[] = [];
  // 1. 放宽题目块匹配：允许##或###、标题后可有任意字符（如“选择题1：”“选择题-1”）
  const questionBlocks =
    markdown.match(
      /#{2,3}\s*选择题\s*[\d\-：:]\s*[\s\S]*?(?=#{2,3}\s*选择题|$)/gi
    ) || [];

  questionBlocks.forEach((block, index) => {
    // 2. 提取题目内容：允许标题后直接跟题目（不强制换行）
    const questionMatch = block.match(
      /#{2,3}\s*选择题\s*[\d\-：:]\s*(.*?)(?=\*\*选项|$)/is
    );
    const question = questionMatch?.[1]?.trim() || `未识别的题目${index + 1}`;

    // 3. 提取选项：允许“选项”标记大小写、有无加粗、冒号格式
    const optionsMatch = block.match(
      /(\*\*|)\s*选项\s*[:：]\s*(\*\*|)\s*([\s\S]*?)(?=\*\*答案|$)/is
    );
    if (!optionsMatch) {
      console.warn(`第${index + 1}题：未找到选项`);
      return;
    }
    const optionsText = optionsMatch[3] || "";
    const options = optionsText
      .split(/\n+/) // 按换行分割
      .filter((line) => line.trim())
      .map((line) => line.replace(/^[A-Da-d]\s*[.:)、]\s*/, "").trim()) // 允许A.、a)、B：等前缀
      .slice(0, 4); // 最多取4个选项

    // 4. 提取答案：允许答案标记大小写、有无加粗、答案带括号/小写
    const answerMatch = block.match(
      /(\*\*|)\s*答案\s*[:：]\s*(\*\*|)\s*([A-Da-d()])/is
    );
    if (!answerMatch) {
      console.warn(`第${index + 1}题：未找到答案`);
      return;
    }
    const answerLetter = answerMatch[3].replace(/[()]/g, "").toUpperCase(); // 去除括号并转大写
    const correctAnswerIndex = ["A", "B", "C", "D"].indexOf(answerLetter);
    if (correctAnswerIndex === -1) {
      console.warn(`第${index + 1}题：答案格式错误（${answerLetter}）`);
      return;
    }

    // 5. 提取解析：放宽解析标记匹配
    const explanationMatch = block.match(
      /(\*\*|)\s*解析\s*[:：]\s*(\*\*|)\s*(.*?)(?=#{2,3}|$)/is
    );
    const explanation = explanationMatch?.[3]?.trim() || "无解析";

    // 6. 放宽选项数量限制（至少2个选项即可）
    if (options.length >= 2) {
      questions.push({
        id: `q${index + 1}`,
        question,
        options,
        correctAnswerIndex,
        explanation,
      });
    } else {
      console.warn(`第${index + 1}题：选项不足（${options.length}个）`);
    }
  });

  console.log("解析后的题目:", questions);
  return questions;
};

const messageList = ref<Message[]>([]);

// generateMessageItem("assistant", "start", "你好，我是ai", "");
const anwser = ref();
const promptId = ref<number>(0);
const answerHandler = async (answer: string) => {
  console.log("chat-index", answer);
  if (answer.trim() === "") {
    alert("请输入内容");
    return;
  }
  // 正则表达式：/关键词1|关键词2/gi（g=全局匹配，i=忽略大小写）
  const regex = /题|出题|练习|测试/gi;
  // 对比关键字
  const isMatch = regex.test(answer);
  generateMessageItem("user", "end", answer, "", formatDate(new Date()), false);
  if (isMatch) {
    // const answers = `
    //   请根据以下主题生成3道Java基础选择题，每道题包含4个选项（A-D）、正确答案和解析：
    //   主题:${answer}￥默认为出java题

    //   格式要求：
    //   \`\`\`markdown
    //   ### 选择题1
    //   题目内容...

    //   **选项：**
    //   A. 选项内容
    //   B. 选项内容
    //   C. 选项内容
    //   D. 选项内容

    //   **答案：** B
    //   **解析：** 解析内容...

    //   ### 选择题2
    //   ...
    //   \`\`\`
    //   `;
    promptId.value = 102;
    // anwser.value = answers;
    anwser.value = answer;
    aiTopics.clearMessages();
    await fetchChat();
  } else if (!isMatch) {
    anwser.value = answer;
    fetchChat();
  }
};
const fetchChat = async function () {
  isLoading.value = true;
  let fullResponse = "";
  let lastIndex: number;
  generateMessageItem(
    "assistant",
    "start",
    "",
    "",
    formatDate(new Date()),
    true
  );
  fetch(
    `${
      import.meta.env.VITE_API_BASE_URL + import.meta.env.VITE_GLOB_API_URL
    }/stream`,
    {
      method: "POST",
      headers: {
        "Content-Type": "application/json",
        Authorization: `Bearer ${userStore.token}`,
        //流式响应
        Accept: "text/event-stream",
      },
      body: JSON.stringify({
        question: anwser.value,
        sessionId: userStore.currentUser.userId,
        promptId: promptId.value,
      }),
    }
  )
    .then(async (response) => {
      lastIndex = messageList.value.length - 1;
      if (!response.ok) {
        messageList.value[lastIndex].content = "网络响应失败，请稍后再试。";

        throw new Error("网络响应失败：" + response.statusText);
      }
      messageList.value[lastIndex].loading = false;
      return response;
    })
    .then(async (result: Response) => {
      if (!result.body) {
        messageList.value[lastIndex].content = "响应体为空，无法读取数据流。";
        throw new Error("响应体为空，无法读取数据流。");
      }
      const reader = result.body.getReader();
      console.log(reader);
      const decoder = new TextDecoder();
      let buffer = "";

      while (true) {
        // console.log(reader.read())
        // debugger
        const { done, value } = await reader.read();
        console.log(done);
        if (done) {
          console.log("流结束");
          isLoading.value = false;
          // 仅在流完全结束后解析
          const questions = parseQuestions(fullResponse);
          aiTopics.setQuestions(questions);
          aiTopics.setLoading(false);

          // 重新启用提交按钮
          if (enableSubmitBtn) {
            enableSubmitBtn();
          }

          break;
        }

        const chunk = decoder.decode(value);
        // console.log(chunk)

        buffer += chunk;
        // console.log('buffer:', buffer)
        const lines = buffer.split("\n");
        // debugger;
        buffer = lines.pop() || ""; // 剩余未处理的数据放回 buffer

        for (const line of lines) {
          console.log(line);
          if (line.startsWith("data:")) {
            try {
              const data = JSON.parse(line.substring(5));
              // console.log("data=====", data);
              if (data.result) {
                // console.log("message:", data.result);
                const tt = data.result.output.text;
                fullResponse += tt;

                //将lastIndex这条消息更新内容
                messageList.value[lastIndex].content += data.result.output.text;
                messageList.value[lastIndex].id =
                  data.result.output.metadata.id;
                console.log(messageList.value);

                if (aiTopics.messageList.length > 0) {
                  aiTopics.messageList[
                    aiTopics.messageList.length - 1
                  ].content += tt;
                }
                // 解析题目
                const questions = parseQuestions(fullResponse);
                aiTopics.setQuestions(questions);
                // console.log(messageList.value);
                scrollBottom();
              }
            } catch (e) {
              console.error("解析错误:", e);
            } finally {
            }
          }
        }
      }
    });
};

function generateMessageItem(
  role: string,
  placement: string,
  content: string,
  id: string,
  createTime: string,
  loading: boolean
) {
  messageList.value.push({
    key: messageList.value.length,
    role,
    placement,
    content,
    createTime,
    noStyle: role === "assistant" ? false : true,
    showBackButton: false,
    id,
    loading,
  });
}
function refreshMessage(item: Message) {
  console.log("refreshMessage", item);
}
function copyHandler(item: Message) {
  const textToCopy = item.content;
  navigator.clipboard
    .writeText(textToCopy)
    .then(() => {
      ElMessage.success("复制成功");
    })
    .catch((err) => {
      console.error("复制失败:", err);
    });
}
function clearMessagesHandler() {
  messageList.value = [];
  clearMessageList(userStore.currentUser.userId);
}
const autoSendMessage = () => {
  const autoMessage = localStorage.getItem("autoSendMessage");
  if (autoMessage) {
    answerHandler(autoMessage);
    localStorage.removeItem("autoSendMessage");
  }
};
const removeMessageHandler = (item: Message) => {
  const res = removeMessage(userStore.currentUser.userId, item.id);
  if (res) {
    messageList.value = messageList.value.filter((msg) => msg.id !== item.id);
    ElMessage.success("删除成功");
  } else {
    ElMessage.error("删除失败，请稍后再试");
  }
  console.log("removeMessageHandler", res);
};
defineExpose({
  answerHandler,
  clearMessagesHandler,
  scrollBottom,
});
</script>

<template>
  <BubbleList
    v-if="messageList && messageList.length > 0"
    :list="messageList"
    :max-height="height"
    ref="bubbleListRef"
  >
    <template #avatar="{ item }">
      <div class="avatar-wrapper">
        <img :src="item.role === 'assistant' ? avartAi : avatar" alt="avatar" />
      </div>
    </template>
    <template #header="{ item }">
      <div class="header-wrapper">
        <div class="header-name">
          {{
            item.role === "assistant"
              ? "云顶AI助手"
              : userStore.currentUser.nickname
          }}
        </div>
      </div>
    </template>
    <template #content="{ item }" :loading="loading">
      <div class="content-wrapper">
        <div class="content-text" v-if="item.role == 'user'">
          {{ item.content }}
        </div>
        <div v-else>
          <XMarkdown
            :markdown="item.content"
            class="markdown-body"
            :themes="{ light: 'github-light', dark: 'github-dark' }"
            default-theme-mode="dark"
          />
        </div>
      </div>
    </template>
    <template #footer="{ item }">
      <div class="footer-wrapper">
        <div class="footer-container">
          <el-button
            type="info"
            :icon="Refresh"
            size="small"
            circle
            @click="refreshMessage(item)"
            v-show="false"
          />
          <el-button
            type="success"
            :icon="Search"
            size="small"
            circle
            v-show="false"
          />
          <!-- 删除 -->
          <el-button
            type="danger"
            :icon="Remove"
            size="small"
            circle
            :disabled="isLoading"
            @click="removeMessageHandler(item)"
          />
          <el-button
            type="warning"
            :icon="Star"
            size="small"
            circle
            v-show="false"
          />
          <el-button
            color="#626aef"
            :icon="DocumentCopy"
            size="small"
            circle
            :disabled="isLoading"
            @click="copyHandler(item)"
          />
        </div>
        <div class="footer-time">
          {{ item.createTime }}
        </div>
      </div>
    </template>
  </BubbleList>
  <div v-else class="empty-chat-container">
    <div class="empty-chat-content">
      <div class="ai-avatar">
        <img :src="avartAi" alt="AI助手" />
      </div>
      <div class="welcome-text">
        <h3>👋 欢迎使用云顶AI助手</h3>
        <p>我是您的智能学习伙伴，可以为您提供以下服务：</p>
      </div>
      <div class="feature-cards">
        <div class="feature-card">
          <div class="feature-icon">📚</div>
          <div class="feature-title">智能出题</div>
          <div class="feature-desc">
            输入关键词"出题"、"练习"等，我会为您生成专业的选择题
          </div>
        </div>
        <div class="feature-card">
          <div class="feature-icon">💬</div>
          <div class="feature-title">智能问答</div>
          <div class="feature-desc">有任何问题都可以问我，我会尽力为您解答</div>
        </div>
        <div class="feature-card">
          <div class="feature-icon">🎯</div>
          <div class="feature-title">学习指导</div>
          <div class="feature-desc">提供个性化的学习建议和知识点解析</div>
        </div>
      </div>
      <div class="start-chat-hint">
        <p>请在下方输入框开始对话吧~ ✨</p>
      </div>
    </div>
  </div>
</template>

<style scoped lang="less">
.avatar-wrapper {
  width: 40px;
  height: 40px;
  img {
    width: 100%;
    height: 100%;
    border-radius: 50%;
  }
}

.header-wrapper {
  .header-name {
    font-size: 14px;
    color: #979797;
  }
}

.content-wrapper {
  .content-text {
    font-size: 14px;
    color: #333;
    padding: 12px;
    background: linear-gradient(to right, #fdfcfb 0%, #ffd1ab 100%);
    border-radius: 15px;
    box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  }
}

.footer-wrapper {
  display: flex;
  align-items: center;
  gap: 10px;
  .footer-time {
    font-size: 12px;
    margin-top: 3px;
  }
}

.footer-container {
  :deep(.el-button + .el-button) {
    margin-left: 8px;
  }
}

.loading-container {
  font-size: 14px;
  color: #333;
  padding: 12px;
  background: linear-gradient(to right, #fdfcfb 0%, #ffd1ab 100%);
  border-radius: 15px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.loading-container span {
  display: inline-block;
  margin-left: 8px;
}

@keyframes bounce {
  0%,
  100% {
    transform: translateY(5px);
  }
  50% {
    transform: translateY(-5px);
  }
}

.loading-container span:nth-child(4n) {
  animation: bounce 1.2s ease infinite;
}
.loading-container span:nth-child(4n + 1) {
  animation: bounce 1.2s ease infinite;
  animation-delay: 0.3s;
}
.loading-container span:nth-child(4n + 2) {
  animation: bounce 1.2s ease infinite;
  animation-delay: 0.6s;
}
.loading-container span:nth-child(4n + 3) {
  animation: bounce 1.2s ease infinite;
  animation-delay: 0.9s;
}

/* 空聊天状态样式 */
.empty-chat-container {
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 60vh;
  padding: 20px;
}

.empty-chat-content {
  text-align: center;
  max-width: 600px;
  width: 100%;
}

.ai-avatar {
  width: 80px;
  height: 80px;
  margin: 0 auto 24px;
  img {
    width: 100%;
    height: 100%;
    border-radius: 50%;
    border: 3px solid #e1e8ed;
    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
  }
}

.welcome-text {
  margin-bottom: 32px;
  h3 {
    font-size: 24px;
    color: #333;
    margin-bottom: 12px;
    font-weight: 600;
  }
  p {
    font-size: 16px;
    color: #666;
    line-height: 1.5;
    margin: 0;
  }
}

.feature-cards {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(180px, 1fr));
  gap: 20px;
  margin-bottom: 32px;
}

.feature-card {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  border-radius: 12px;
  padding: 20px;
  color: white;
  transition: transform 0.3s ease, box-shadow 0.3s ease;
  cursor: pointer;

  &:hover {
    transform: translateY(-4px);
    box-shadow: 0 8px 25px rgba(102, 126, 234, 0.3);
  }

  &:nth-child(2) {
    background: linear-gradient(135deg, #f093fb 0%, #f5576c 100%);
    &:hover {
      box-shadow: 0 8px 25px rgba(240, 147, 251, 0.3);
    }
  }

  &:nth-child(3) {
    background: linear-gradient(135deg, #4facfe 0%, #00f2fe 100%);
    &:hover {
      box-shadow: 0 8px 25px rgba(79, 172, 254, 0.3);
    }
  }
}

.feature-icon {
  font-size: 32px;
  margin-bottom: 12px;
}

.feature-title {
  font-size: 16px;
  font-weight: 600;
  margin-bottom: 8px;
}

.feature-desc {
  font-size: 14px;
  opacity: 0.9;
  line-height: 1.4;
}

.start-chat-hint {
  p {
    font-size: 16px;
    color: #888;
    margin: 0;
    padding: 16px 24px;
    background: #f8f9fa;
    border-radius: 25px;
    display: inline-block;
    border: 1px solid #e9ecef;
  }
}

/* 响应式适配 */
@media (max-width: 768px) {
  .empty-chat-container {
    min-height: 50vh;
    padding: 16px;
  }

  .feature-cards {
    grid-template-columns: 1fr;
    gap: 16px;
  }

  .welcome-text h3 {
    font-size: 20px;
  }

  .welcome-text p {
    font-size: 14px;
  }
}
</style>
